<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">调拨单编辑</p>
    </div>
    <div class="view-container">
      <el-row class="status-title">
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm(1)"
          >保存</el-button>
        </el-col>
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm(2)"
          >提交</el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="mt30">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编码:" prop="code">
              <el-input v-model="form.code" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务日期:" prop="businessDate">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.businessDate" suffix-icon="el-icon-date" type="datetime" placeholder="系统自动生成，获取当前日期时间" style="width:100%;" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="调出公司:" prop="outCompanyName">
              <el-select v-model="form.outCompanyName" placeholder="请选择" style="width:100%;" filterable @change="val => onPlatForm(val, 'out')">
                <el-option v-for="(item,index) of customerDeptList" :key="index" :label="item.orgName" :value="item.orgName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调出部门:" prop="outCompanyDept">
              <el-select v-model="form.outCompanyDept" placeholder="请选择" style="width:100%;" filterable :disabled="outDisabled">
                <el-option v-for="(item,index) of outCompanyDeptList" :key="index" :label="item.deptName" :value="item.deptName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调出仓库:" prop="outWarehouseName">
              <el-select v-model="form.outWarehouseName" style="width:100%;" placeholder="请选择" filterable @change="val => onWarehouse(val, 'out')">
                <el-option
                    v-for="item in warehouseList"
                    :key="item.warehouseId"
                    :label="item.name"
                    :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="调入公司:" prop="inCompanyName">
              <el-select v-model="form.inCompanyName" placeholder="请选择" style="width:100%;" filterable @change="val => onPlatForm(val, 'in')">
                <el-option v-for="(item,index) of customerDeptList" :key="index" :label="item.orgName" :value="item.orgName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调入部门:" prop="inCompanyDept">
              <el-select v-model="form.inCompanyDept" placeholder="请选择" style="width:100%;" filterable :disabled="inDisabled">
                <el-option v-for="(item,index) of inCompanyDeptList" :key="index" :label="item.deptName" :value="item.deptName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调入仓库:" prop="inWarehouseName">
              <el-select v-model="form.inWarehouseName" style="width:100%;" placeholder="请选择" filterable @change="val => onWarehouse(val, 'in')">
                <el-option
                    v-for="item in warehouseList"
                    :key="item.warehouseId"
                    :label="item.name"
                    :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="调拨原因:" prop="transferReason">
              <el-input v-model="form.transferReason" type="textarea" :rows="2" placeholder="调拨原因" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="productData">
              <el-table-column label="序号" type="index" align="center" width="50" />
              <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                <template slot-scope="scope">
                  <template v-if="item.type == '1'">
                    <el-input placeholder="请选择" v-model="scope.row[item.prop]" @focus="productShow" />
                  </template>
                  <template v-if="item.type == '2'">{{ scope.row[item.prop] }}</template>
                  <template v-if="item.type == 'transferNum'">
                    <el-input placeholder="请输入数量" v-model.number="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                  </template>
                  <template v-if="item.type == '3'">
                    <el-input placeholder="备注" v-model="scope.row[item.prop]" />
                  </template>
                  <span class="del" v-if="item.type == 'del'" @click="deleteRow(scope.row, scope.$index)">删除</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row class="mt20">
          <el-col :span="8">
            <el-form-item label="合计数量:" prop="total">
              <el-input v-model="form.total" placeholder="系统自动合计" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 产品弹出对话框 -->
    <el-dialog title="产品" :visible.sync="open" width="1000px" top="50px" append-to-body center>
        <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
          <el-form-item prop="searchValue">
            <el-input
              v-model="queryParams.searchValue"
              placeholder="名称或者编码模糊查询"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="searchProduct" @row-click="handleSelect" >
          <el-table-column label="序号" type="index" align="center" width="50">
            <template slot-scope="scope">
              <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="SKU编码" align="center" prop="specificationCode" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="SKU名称" align="center" prop="specificationName" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
          <el-table-column label="是否启用扫码" align="center" prop="isSerial" width="120">
            <template slot-scope="scope">
              <div v-if="scope.row.isSerial == '0'" style="color:#13C2C2">是</div>
              <div v-if="scope.row.isSerial == '1'" style="color:#52C41A">否</div>
              <div v-else></div>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="approvalStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus == 0" style="color:#13C2C2"></div>
              <div v-if="scope.row.approvalStatus == 1" style="color:#13C2C2">待审核</div>
              <div v-if="scope.row.approvalStatus == 2" style="color:#52C41A">已通过</div>
              <div v-if="scope.row.approvalStatus == 3" style="color:#fd562c">拒绝</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="productStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.productStatus == 0" style="color:#13C2C2">禁用</div>
              <div v-if="scope.row.productStatus == 1" style="color:#52C41A">正常</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getSearchProduct()"
        />
    </el-dialog>
  </div>
</template>

<script>
import { transferOrderAdd, transferOrderEdit, transferOrderDetail } from "@/api/system/transferOrder/transferOrder"
import { deptTree } from "@/api/system/order/order"
import { listProduct} from "@/api/system/basicdata/basicdata"
import { queryWarehouse } from "@/api/system/warehouse/warehouse"
export default {
  name: "edit",
  data(){
    return {
      form: {
        code: '', // 单据编码
        businessDate: '', // 业务日期
        outCompanyId: '', // 调出公司id
        outCompanyName: '', // 调出公司名称
        outCompanyDept: '', // 调出部门
        outWarehouseId: '', // 调出仓库id
        outWarehouseName: '', // 调出仓库名称
        inCompanyId: '', // 调入公司id
        inCompanyName: '', // 调入公司名称
        inCompanyDept: '', // 调入部门
        inWarehouseId: '', // 调入仓库id
        inWarehouseName: '', // 调入仓库名称
        transferReason: '', // 调拨原因
        detailList: [], // 商品数据
        total: '', // 合计数量
      },
      // 表头
      columns: [{
        prop: "specificationCode",
        label: "货品编码",
        width: 200,
        type: '1'
      },{
        prop: "specificationName",
        label: "货品名称",
        width: 200,
        type: '1'
      },{
        prop: "specification",
        label: "规格",
        width: 180,
        type: '2'
      },{
        prop: "unit",
        label: "单位",
        width: 100,
        type: '2'
      },
      // {
      //   prop: "unitPrice",
      //   label: "单价",
      //   width: 120,
      //   type: '2'
      // },
      {
        prop: "transferNum",
        label: "调拨数量",
        width: 120,
        type: 'transferNum'
      },
      // {
      //   prop: "totalPrice",
      //   label: "总价",
      //   width: 100,
      //   type: '2'
      // },
      {
        prop: "remark",
        label: "备注",
        width: 200,
        type: '3'
      },{
        label: "",
        type: 'del',
        width: 80
      }],
      // 表格数据
      productData: [{
        specificationId: '', // 货品id
        specificationCode: '', // 货品编码
        specificationName: '', // 货品名称
        specification: '', // 规格
        unit: '', // 单位
        // unitPrice: '', // 单价
        transferNum: '', // 调拨数量
        // totalPrice: '', // 总价
        remark: '', // 备注
      }],
      id: '',
      // 产品数据
      searchProduct: [],
      open: false,
      // 查询参数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productStatus : 1,
        approvalStatus: 2,
        searchValue: undefined
      },
      customerDeptList: [], // 公司列表
      outCompanyDeptList: [], // 部门列表
      inCompanyDeptList: [],
      warehouseList: [], // 仓库列表
      outDisabled: true,
      inDisabled: true,
      rules: {
        outCompanyName: [
          { required: true, message: "调出公司不能为空", trigger: "change"}
        ],
        outWarehouseName: [
          { required: true, message: "调出仓库不能为空", trigger: "change" }
        ],
        inCompanyName: [
          { required: true, message: "调入公司不能为空", trigger: "change" }
        ],
        inWarehouseName: [
          { required: true, message: "调入仓库不能为空", trigger: "change" }
        ],
      },
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getDetailData()
    this.getDeptTree()
    this.getWarehouseList()
  },
  methods:{
    // 获取详情信息
    getDetailData() {
      transferOrderDetail(this.id).then(res => {
        this.form = res.data
        if(res.data.detailList == null){
          this.productData = []
        }else{
          this.productData = res.data.detailList
        }
        this.addProduct()
      })
    },
    // 获取公司
    getDeptTree(){
      deptTree().then(res => {
        this.customerDeptList = res.data
        if(this.form.outCompanyDept !== null && this.form.outCompanyDept !== ''){
          let data = this.customerDeptList.find(item => item.id == this.form.outCompanyId)
          this.outCompanyDeptList = data.deptList
        }
        if(this.form.inCompanyDept !== null && this.form.inCompanyDept !== ''){
          let data = this.customerDeptList.find(item => item.id == this.form.inCompanyId)
          this.inCompanyDeptList = data.deptList
        }
      })
    },
    // 选择公司
    onPlatForm(item, type){
      let data = this.customerDeptList.find(i => i.orgName == item)
      if(type == 'out'){
        this.form.outCompanyId = data.id
        this.form.outCompanyName = data.orgName
        if(data.deptList !== null){
          this.outDisabled = false
          this.outCompanyDeptList = data.deptList
        }else{
          this.outDisabled = true
          this.outCompanyDeptList = []
          this.form.outCompanyDept = ''
        }
      }else{
        this.form.inCompanyId = data.id
        this.form.inCompanyName = data.orgName
        if(data.deptList !== null){
          this.inDisabled = false
          this.inCompanyDeptList = data.deptList
        }else{
          this.inDisabled = true
          this.inCompanyDeptList = []
          this.form.inCompanyDept = ''
        }
      }
    },
    // 获取仓库列表
    getWarehouseList(){
      queryWarehouse().then(res => {
        if(res.code == 200){
          this.warehouseList = res.data
        }
      })
    },
    // 仓库选择
    onWarehouse(item, type){
      let data = this.warehouseList.find(i => i.name == item)
      if(type == 'out'){
        this.form.outWarehouseId = data.warehouseId
        this.form.outWarehouseName = data.name
      }else{
        this.form.inWarehouseId = data.warehouseId
        this.form.inWarehouseName = data.name
      }
    },
    // 显示所有货品
    productShow(){
      this.open = true
      this.getSearchProduct()
    },
    // 获取产品信息
    getSearchProduct(){
      listProduct(this.addDateRange(this.queryParams)).then(res => {
        this.searchProduct = res.rows
        this.total = res.total
      })
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getSearchProduct()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 选中
    handleSelect(item){
      // console.log(item)
      let obj = {
        specificationId: item.productSpecificationsId,
        specificationCode: item.specificationCode,
        specificationName: item.specificationName,
        specification: item.value1 !== null ? item.value1 + item.value2 : '',
        unit: item.unit,
        remark: item.remark,
      }
      let index = this.productData.findIndex(i => i.specificationCode == item.specificationCode)
      if(index > -1){
        this.$modal.msgError('货品已存在，请重新选择！')
        this.open = true
      }else{
        this.productData.push(obj)
        this.open = false
      }
      let arr = this.productData.filter(item => item.specificationCode !== '')
      this.productData = arr
      this.addProduct()
    },
    // 数量验证
    inputNum(val, row){
      if(Number(val) > 0){
        this.totalData()
      }else{
        this.$modal.msgError('调拨数量必须大于0!')
        row.transferNum = ''
        this.totalData()
      }
    },
    // 添加一条产品信息
    addProduct(){
      let data = {
        key: {
          orderId: this.id ? this.id : '',
        }
      }
      this.columns.forEach(item =>{
        data.key[item.prop] = ''
      })
      this.productData.push(JSON.parse(JSON.stringify(data.key)))
    },
    // 删除数据
    deleteRow(item, index){
      if(item.specificationCode !== ''){
        this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
          // if(item.id && item.id !== '' || item.id !== undefined){
          //   delProduct(item.id).then(res => {
          //     if(res.code == 200){
          //       this.getDetailData()
          //       this.totalData()
          //     }
          //   })
          // }else{
            this.productData.splice(index, 1)
            this.totalData()
          // }
        }).catch(() => {})
      }else{
        this.$modal.msgError('最少保留一条可编辑数据！')
      }
    },
    // 合计
    totalData(){
      let total = 0
      this.productData.forEach(item => {
          total += Number(item.transferNum)
          return (total)
      })
      this.form.total = total
    },
    // 提交数据
    submitForm(e) {
      // console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 过滤掉空数据
          let arr = this.productData.filter(item => item.specificationCode !== '')
          let num = arr.every(val => !!val.transferNum)
          this.form.detailList = arr
          if(e == 1){
            // 保存
            let arr = this.form
            arr.id = this.id
            arr.status = 0
            this.$modal.loading("正在保存")
            transferOrderEdit(arr).then(res=> {
              if(res.code == 200){
                this.getDetailData()
                this.$modal.closeLoading()
                this.$modal.msgSuccess("保存成功")
              }
            })
          }else{
            if(arr.length > 0){
              if(num == true){
                // 提交
                let arr = this.form
                arr.id = this.id
                arr.status = 1
                this.$modal.loading("正在提交")
                transferOrderEdit(arr).then(res=> {
                  if(res.code == 200){
                    this.$refs.form.resetFields()
                    this.$tab.closeOpenPage({ path: "/warehouseManagement/warehouse/transferOrder" })
                    this.$modal.closeLoading()
                    this.$modal.msgSuccess("新建成功")
                  }
                })
              }else{
                this.$modal.msgError('调拨数量不能为空！')
              }
            }else{
              this.$modal.msgError('请选择货品！')
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.del{
  color: #ff0000;
  cursor: pointer;
}
</style>